<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
        integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">

    <!-- jquery -->
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>

    <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"
        integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd"
        crossorigin="anonymous"></script>
</head>

<body>
    <div id="box">
        <button id="addGoods">添加商品</button>
        <hr />
        <div class="search-box">
            <span class="name">商品名称:</span>
            <input type="text" id="goodsName" />
            <button id="searchBtn">搜索</button>
        </div>
    </div>

    <div class="goods-table">
        <table class="table table-bordered table-hover">
            <thead>
                <tr>
                    <th><input class="chk" type="checkbox" id="all" /></th>
                    <th>ID</th>
                    <th>商品</th>
                    <th class="mouseclick">价格</th>
                    <th class="mouseclick">库存</th>
                    <th class="mouseclick">销量</th>
                    <th>创建时间</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
        <button id="dels">删除选中</button>
    </div>
    <div class="addGoods">
        商品名称： <input type="text" id="addGoodsName" />
        <br />
        商品库存：
        <input type="text" id="addGoodsStock" /><br />
        商品销量： <input type="text" id="addGoodsSold" /> <br />商品价格：
        <input type="text" id="addGoodsPrice" /> <br />是否上架：
        <input type="radio" name="isOnLine" checked value="1" />上架<input type="radio" name="isOnLine" value="2" />下架
        <br />商品图片：
        <input type="text" id="addGoodsImg" />
        <br />
        <div class="addBtnStatus">
            <button id="addBtn">确定添加</button>
            <button id="offBtn">取消添加</button>
        </div>
        <div class="saveBox">
            <button id="saveBtn">保存</button>
            <button id="offSaveBtn">取消</button>
        </div>
    </div>
    <div class="tips">提示: <span id="tips">获取数据失败</span></div>
    <div class="mask"></div>
</body>
<script src="ajax.js"></script>
<script>
    let thisId = null
    $(function () {
        //获取商品数据
        getGoodsData()
        //添加商品
        $('#addGoods').on('click', function () {
            showAddGoodsBox()
        })
        // document.getElementById('addGoods').onclick = showAddGoodsBox
        //取消添加
        $('#offBtn').on('click', function () {
            offAddGoodsBox()
        })
        $('.mask').on('click', function () {
            offAddGoodsBox()
        })
        $('#offSaveBtn').on('click', function () {
            offAddGoodsBox()
        })
        // document.getElementById('offBtn').onclick = offAddGoodsBox
        // document.querySelector('.mask').onclick = offAddGoodsBox
        // document.getElementById('offSaveBtn').onclick = offAddGoodsBox
        //确定添加
        $('#addBtn').on('click', function () {
            addGoods()
        })
        // document.getElementById('addBtn').onclick = addGoods
        //tbody
        $('tbody').on('click', function () {
            tbodyFun()
        })
        // var tbody = document.querySelector('tbody')
        // tbody.onclick = tbodyFun
        //保存
        $('#saveBtn').on('click', function () {
            saveGoods()
        })
        // document.getElementById('saveBtn').onclick = saveGoods
        //搜索
        $('#goodsName').on('click', function () {
            searchFun()
        })
        $('#searchBtn').on('click', function () {
            searchFun()
        })
        // document.getElementById('goodsName').onkeyup = searchFun
        // document.getElementById('searchBtn').onclick = searchFun
        //全选
        $('#all').on('click', function () {
            allFun()
        })
        // document.getElementById('all').onchange = allFun
        //批量删除选中
        $('#dels').on('click', function () {
            delsFun()
        })
        $('.mouseclick:eq(0)').on('click', function () {
            sortFun()
        })
        $('.mouseclick:eq(1)').on('click', function () {
            sortFun()
        })
        $('.mouseclick:eq(2)').on('click', function () {
            sortFun()
        })
        // document.getElementById('dels').onclick = delsFun
        // document.querySelectorAll('.mouseclick')[0].onclick = sortFun
        // document.querySelectorAll('.mouseclick')[1].onclick = sortFun
        // document.querySelectorAll('.mouseclick')[2].onclick = sortFun
    })
    //声明变量
    let sortObj = {
        price: 'asc',
        stock: 'asc',
        sold: 'asc',
    }
    //
    function sortFun() {
        let data = {
            page: 1,
            limit: 1000,
        }
        if (this.innerHTML == '价格') {
            data.type = 'price'
            data.sort = sortObj.price == 'asc' ? 'desc' : 'asc'
            sortObj.price = data.sort
        }
        if (this.innerHTML == '库存') {
            data.type = 'stock'
            data.sort = sortObj.stock == 'asc' ? 'desc' : 'asc'
            sortObj.stock = data.sort
        }
        if (this.innerHTML == '销量') {
            data.type = 'sold'
            data.sort = sortObj.sold == 'asc' ? 'desc' : 'asc'
            sortObj.sold = data.sort
        }
        $.ajax({
            url: 'https://liu.zzgoodqc.cn/goods/sort',
            data: data,
            dataType: 'json',
            success: function (res) {
                if (res.code == 200) {
                    rendder(res.data)
                } else {
                    showTips(res.msg, 'red')
                }
            },
        })
    }
    //批量删除
    function delsFun() {
        let checkedObj = Array.from(
            $('.chk:checked')
        )
        checkedObj.forEach((item) => {
            let id = item.getAttribute('data-id')
            delGoods(id, item)
        })
    }
    function allFun() {
        let checkAll = this.checked
        let chk = Array.from($('chk'))
        chk.forEach((item) => {
            item.checked = checkAll
        })
    }
    //商品搜索
    function searchFun() {
        // 获取搜索框的值
        if (event.keyCode == 13 || event.type == 'click') {

            let wd = $('#goodsName').val()
            //获取商品数据
            if (wd) {
                $.ajax({
                    url: 'https://liu.zzgoodqc.cn/goods/search',
                    type: 'post',
                    data: {
                        goods_name: wd,
                    },
                    dataType: 'json',
                    success: function (res) {
                        if (res.code == 200) {
                            rendder(res.data)
                        } else {
                            showTips(res.msg, 'red')
                        }
                    },
                })
            } else {
                getGoodsData()
            }
        }
    }
    function saveGoods() {
        let status = $(
            'input[name="isOnLine"]:checked'
        ).val()
        let goodsData = {
            id: thisId,
            goods_name: addGoodsName.value || '小八爪鱼',
            stock: addGoodsStock.value || 100,
            price: addGoodsPrice.value || 100,
            status: status || 1,
            sold: addGoodsSold.value || 100,
            img:
                addGoodsImg.value ||
                'https://img14.360buyimg.com/n7/jfs/t1/206184/37/26048/63725/62fc9493E51311fa7/c37c6193ac9e62be.jpg',
        }
        $.ajax({
            type: 'post',
            url: 'https://liu.zzgoodqc.cn/goods/update',
            data: goodsData,
            dataType: 'json',
            success: function (res) {
                if (res.code == 200) {
                    showTips('修改成功', 'green')
                    $('.addBtnStatus').show();
                    $('.saveBox').hide();
                    offAddGoodsBox()
                    getGoodsData()
                }
            },
        })
    }
    function tbodyFun() {
        if (event.target.nodeName == 'A') {
            event.preventDefault()
            let id = event.target.getAttribute('data-id')
            if (event.target.innerHTML == '删除') {
                if (confirm('确定删除吗？')) {
                    delGoods(id, event.target)
                }
            }
            if (event.target.innerHTML == '编辑') {
                editGoods(id)
            }
        }
    }
    function editGoods(id) {
        $.ajax({
            url: 'https://liu.zzgoodqc.cn/goods/detail?id=' + id,
            dataType: 'json',
            success: function (res) {
                if (res.code == 200) {
                    thisId = id
                    addGoodsName.value = res.data.goods_name
                    addGoodsStock.value = res.data.stock
                    addGoodsSold.value = res.data.sold
                    addGoodsPrice.value = res.data.price
                    addGoodsImg.value = res.data.img
                    if (res.data.status == 1) {
                        $(
                            'input[name="isOnLine"][value="1"]'
                        ).checked = true
                    } else {
                        $(
                            'input[name="isOnLine"][value="2"]'
                        ).checked = true
                    }
                    $('.addBtnStatus').hide()
                    $('.saveBox').show()
                    showAddGoodsBox()
                }
            },
        })
    }
    function delGoods(id, obj) {
        $.ajax({
            url: 'https://liu.zzgoodqc.cn/goods/delete?id=' + id,
            dataType: 'json',
            success: function (res) {
                if (res.code == 200) {
                    showTips('删除成功', 'green')
                    obj.parentNode.parentNode.parentNode.removeChild(
                        obj.parentNode.parentNode
                    )
                }
            },
        })
    }
    function addGoods() {
        let status = $(
            'input[name="isOnLine"]:checked'
        ).val()
        let goodsData = {
            goods_name: addGoodsName.value || '小八爪鱼',
            stock: addGoodsStock.value || 100,
            price: addGoodsPrice.value || 100,
            status: status || 1,
            sold: addGoodsSold.value || 100,
            img:
                addGoodsImg.value ||
                'https://img14.360buyimg.com/n7/jfs/t1/206184/37/26048/63725/62fc9493E51311fa7/c37c6193ac9e62be.jpg',
        }
        $.ajax({
            url: 'https://liu.zzgoodqc.cn/goods/add',
            type: 'post',
            data: goodsData,
            dataType: 'json',
            success: function (res) {
                if (res.code == 200) {
                    showTips('添加成功', 'green')
                    setTimeout(() => {
                        offAddGoodsBox()
                        getGoodsData()
                    }, 2000)
                } else {
                    showTips('添加失败-' + res.msg, 'red')
                }
            },
        })
    }

    function showTips(msg, bgcolor) {
        tips.innerHTML = msg
        $('.tips').css('background', bgcolor)
        $('.tips').show()
        setTimeout(() => {
            $('.tips').hide()
        }, 2000)
    }
    function offAddGoodsBox() {
        $('.addGoods').hide()
        $('.mask').hide()
    }
    function showAddGoodsBox() {
        const addBox = $('.addGoods')
        addBox.show()
        const mask = $('.mask')
        mask.show()
    }
    function getGoodsData() {
        $.ajax({
            url: 'https://liu.zzgoodqc.cn/goods/goodslist',
            type: 'get',
            dataType: 'json',
            success: function (res) {
                if (res.code == 200) {
                    rendder(res.data)
                } else {
                    tips.innerHTML = res.msg
                    $('.tips').show()
                }
            },
        })
    }
    function rendder(data) {
        if (data.length == 0) {
            $('tbody').innerHTML =
                '<tr><th colspan="8" style="color:#ccc;font-size:23px;">暂无数据</th></tr>'
            return
        }
        // data.sort((a, b) => {
        //     return b.id - a.id
        // })
        let html = ''
        data.forEach((item, index) => {
            html += `<tr>
                        <td><input type="checkbox" class='chk' name="chk" data-id="${item.id
                }"/></td>
                        <td>${item.id}</td>
                        <td><img src="${item.img}">${item.goods_name}</td>
                        <td style="font-weight: bold;">￥${item.price}</td>
                        <td>${item.stock}</td>
                        <td>${item.sold}</td>
                        <td>${getDate(item.created_at)}</td>
                        <td>
                            <a href="#" data-id="${item.id}">编辑</a>
                            <a href="#" data-id="${item.id}">删除</a>
                        </td>
                    </tr>`
        })
        $('tbody').html(html)
    }
    function getDate(dates) {
        let created_at = new Date(dates)
        return (
            created_at.getFullYear() +
            '-' +
            (created_at.getMonth() + 1) +
            '-' +
            created_at.getDate() +
            ' ' +
            created_at.getHours() +
            ':' +
            created_at.getMinutes() +
            ':' +
            created_at.getSeconds()
        )
    }
</script>
<style>
    * {
        margin: 0;
        padding: 0;
    }

    button {
        color: white;
        background-image: linear-gradient(120deg,
                #a1c4fd 0%,
                #c2e9fb 100%);
        border: none;
        border-radius: 5rem;
        width: 6rem;
        height: 2.4rem;
        cursor: pointer;
    }

    body {
        display: flex;
        background-color: #f5f5f5;
        flex-wrap: wrap;
        position: relative;
        font-family: 'Microsoft YaHei';
    }

    #box {
        width: 81.3rem;
        height: 20rem;
        height: auto;
        margin: auto;
        background-color: white;
    }

    #addGoods {
        margin: 20px;
        background-image: linear-gradient(120deg, #e0c3fc 0%, #8ec5fc 100%);
        font-size: 1rem;
    }

    hr {
        height: 1px;
        width: 96%;
        border: none;
        background-color: #ccc;
    }

    .search-box {
        width: 100%;
        height: 3.5rem;
        /* padding-left: 40px; */
        padding-top: 1.3rem;
        background-image: linear-gradient(to top, #fbc2eb 0%, #a6c1ee 100%);
    }

    #searchBtn {
        width: 6rem;
        height: 2.5rem;
        background-image: linear-gradient(120deg, #e0c3fc 0%, #8ec5fc 100%);
        font-size: 1.1rem;
    }

    #goodsName {
        width: 11rem;
        height: 2rem;
        border: 1px solid #ccc;
    }

    .goods-table {
        width: 81.3rem;
        min-height: 20rem;
        margin: auto;
        margin-top: 10px;
        /* background-color: white; */
        /* background-image: linear-gradient(to right, #eea2a2 0%, #bbc1bf 19%, #57c6e1 42%, #b49fda 79%, #7ac5d8 100%); */
        /* background-image: linear-gradient(-225deg, #69EACB 0%, #EACCF8 48%, #6654F1 100%); */
        padding-bottom: 50px;
        /* background: url('http://pic.bizhi360.com/bbpic/97/11097.jpg') no-repeat;
        background-size: 100% 100%; */
        /* //隐藏水平滚动条 */
        overflow-x: hidden;
    }

    table {
        width: 100%;
        margin-top: 1.4rem;
        border-collapse: collapse;
    }

    .chk {
        width: 15px;
        height: 15px;
    }

    tr {
        width: 100%;
        height: 10px;
        /* border-bottom: 1px solid rgb(240, 240, 240); */
    }

    th {
        /* padding-bottom: 20px; */
        text-align: center;
    }

    td {
        text-align: center;

    }

    tbody tr {
        height: 10px;
        line-height: 80px;
    }

    a {
        text-decoration: none;
        color: linear-gradient(-225deg, #69EACB 0%, #EACCF8 48%, #6654F1 100%);
    }

    .tips {
        width: 300px;
        height: 50px;
        font-size: 17px;
        color: white;
        background-color: #ee609c;
        border-radius: 5px;
        text-align: center;
        line-height: 50px;
        position: absolute;
        top: 3%;
        left: 40%;
        display: none;
        z-index: 9999;
    }

    img {
        width: 80px;
        height: 80px;
        vertical-align: middle;
    }

    .addGoods {
        width: 25rem;
        height: 25rem;
        color: #a1c4fd;
        background-color: white;
        position: absolute;
        top: 4%;
        left: 35%;
        z-index: 999;
        border-radius: 10px;
        font-weight: bold;
        padding: 30px;
        display: none;
    }

    .addGoods input {
        width: 11rem;
        height: 2rem;
        border: 1px solid #ccc;
        margin-top: 1rem;
    }

    .addGoods input[name='isOnLine'] {
        width: 15px;
        height: 15px;
        margin-top: 10px;
        margin-left: 10px;
    }

    .mask {
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
        position: absolute;
        top: 0;
        left: 0;
        display: none;
    }

    #addBtn {
        display: block;
        float: left;
        margin-left: 30px;
    }

    #offBtn {
        display: block;
        margin-top: 40px;
        margin-left: 150px;
    }

    #saveBtn {
        display: block;
        float: left;
        margin-left: 30px;
    }

    .addBtnStatus {
        display: block;
        margin-top: 40px;
    }

    .saveBox {
        display: none;
        margin-top: 40px;
    }

    #offSaveBtn {
        display: block;
        margin-top: 40px;
        margin-left: 150px;
    }

    #dels {
        margin-top: 20px;
        margin-left: 10px;
        background-image: linear-gradient(120deg, #e0c3fc 0%, #8ec5fc 100%);
    }

    .mouseclick {
        cursor: pointer;
        color: #ee609c;
    }

    .mouseclick:hover {
        color: #a1c4fd;
    }

    .name {
        font-size: 1.5rem;
        font-weight: 600;
        padding-left: 1.5rem;
    }
</style>

</html>